//
//  YAYIOrderRefundsController.m
//  YAYIDoctor
//
//  Created by hxp on 16/5/6.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIOrderRefundsController.h"
#import "YAYINoPayOrderModel.h"
#import "YAYIAvatarCell.h"
#import "YAYIGroupModel.h"
#import "YAYIListView.h"
#import "YAYIOrderRefundsCell.h"
#import "MYLabel.h"
#import "YAYIActionSheet.h"
#import "YAYIPatienInfoController.h"

#import "YAYITableView.h"


@interface YAYIOrderRefundsController ()<UITableViewDelegate,UITableViewDataSource,YAYIAlertViewDelegate,UITextViewDelegate,YAYIListViewDelegate,UITextFieldDelegate, UIAlertViewDelegate, YAYIActionSheetDelegate>


@property (nonatomic,strong)YAYITableView *tableView;
@property (nonatomic,strong)UITextView *textView;
@property (nonatomic,strong)UILabel *time;
@property (nonatomic,strong)UILabel *patient;
@property (nonatomic,strong)UILabel *phone;
@property (nonatomic,strong)UILabel *hospital;
@property (nonatomic,strong)UILabel *money;
@property (nonatomic,strong)YAYIListView *listView;
@property (nonatomic,strong)YAYIAlertView *alertView;
@property (nonatomic,strong)NSMutableArray *dataAry;
@property (nonatomic,strong)UILabel *count;
@property (nonatomic,strong)UILabel *placeholder;

@property (nonatomic, weak) UITextField *realRefundsTF;

@property (nonatomic, strong) NSMutableArray *refundsReasonArray;

/**
 *  退款原因
 */
@property (nonatomic, strong)NSString *type;

/** 修改后的的金额  */
@property (nonatomic, copy) NSString *latestPrice;
/** 实退金额  */
@property (nonatomic, copy) NSString *realRefunds;
/** 已退金额  单位分*/
@property (nonatomic, assign) NSInteger hadRefundAmount;

@end

@implementation YAYIOrderRefundsController

- (void)setLatestPrice:(NSString *)latestPrice
{
    _latestPrice = latestPrice;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    YAYIOrderRefundsCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.moneyText.text = latestPrice;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataAry = [NSMutableArray array];
    self.latestPrice = self.totalPrice;
    self.realRefunds = @"0";
    self.refundsReasonArray = [NSMutableArray array];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    [self setupNav];
    [self orderDetail];
    [self createDataSource];
    [self createTableView];
    
    if (self.noPayModel) {
        [self getRefunds];
    }
    [self getUserInfo];
    
    if (self.pageType == PageTypeRedund)
    {
        [self getOrderInfo];
    }
}



-(void)setupNav
{
    if (self.pageType == PageTypeHadPay || self.pageType == PageTypeRedund) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"提交" forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 60, 30);
        [button addTarget:self action:@selector(onSubmitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:font18];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    }
}


-(void)remoView
{
    self.listView = nil;
    [self.listView removeFromSuperview];

}
-(void)createHudView:(NSString *)msg
{
    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
    [hud setMessage:msg];
    [[UIApplication  sharedApplication].keyWindow addSubview:hud];
    [hud removeFromSuperview:YES time:1 isHinden:YES];
}


-(void)orderDetail
{
    [YAYINetWorking getWithURL:didPay_order_detail_url param:@{@"orderid": self.orderid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if ([dict[@"status"] isEqualToString:@"success"]) {
            
            NSDictionary *map = dict[@"map"];
            NSArray *order = map[@"order"];
            for (NSDictionary *obj in order) {
                YAYINoPayOrderModel *model = [YAYINoPayOrderModel new];
                [model setValuesForKeysWithDictionary:obj];
                self.time.attributedText = [NSString content:@"时间" name:[NSString timeString:model.createtime]];
                self.patient.attributedText = [NSString content:@"病人" name:model.patientname];
                self.phone.attributedText = [NSString content:@"联系电话" name:model.userMobile];
                self.hospital.text = model.hospitalname;
                CGFloat price = [model.totalprice doubleValue] - [model.reduce doubleValue];
                self.money.attributedText = [NSString content:@"费用" name:[NSString stringWithFormat:@"¥%.2lf",price/100.0]];
            }
        }
    }];
    
}


-(UIView *)footerView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignFirstResponderAction:)];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 350)];
    [footerView addGestureRecognizer:tap];
    footerView.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    
    UIView *contentView = [[UIView  alloc] initWithFrame:CGRectMake(0, 10, SCREEN_width, 348)];
    contentView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:contentView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 60, 20)];
    label.textColor = YAYIColor(87, 85, 85);
    label.font = [UIFont systemFontOfSize:font16];
    label.text = @"备注";
    [contentView addSubview:label];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(CGRectGetMinX(label.frame), CGRectGetMaxY(label.frame) + 10, SCREEN_width - 20 *2, 90)];
    self.textView.font = [UIFont systemFontOfSize:15];
    self.textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView.layer.borderWidth = 1;
    self.textView.layer.cornerRadius = 3;
    self.textView.tag = 200;
    self.textView.delegate = self;
    self.textView.clipsToBounds = YES;
    [contentView addSubview:self.textView];
    
    self.placeholder = [UILabel new];
    self.placeholder.font = [UIFont systemFontOfSize:font15];
    self.placeholder.textColor = [UIColor lightGrayColor];
    self.placeholder.textAlignment = NSTextAlignmentLeft;
    self.placeholder.text = @"请填写备注信息";
    [contentView addSubview:self.placeholder];
    [self.placeholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textView.mas_left).offset(5);
        make.top.mas_equalTo(self.textView.mas_top).offset(12);
        make.size.mas_equalTo(CGSizeMake(180, 10));
    }];
    
    
    self.count = [UILabel new];
    self.count.font = [UIFont systemFontOfSize:font14];
    self.count.textColor = [UIColor lightGrayColor];
    self.count.textAlignment = NSTextAlignmentRight;
    self.count.text = @"0 / 50字";
    [contentView addSubview:self.count];
    [self.count mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.textView.mas_right).with.offset(-4);
        make.bottom.mas_equalTo(self.textView.mas_bottom).with.offset(-4);
        make.size.mas_equalTo(CGSizeMake(180, 10));
    }];
    
    
    
    MYLabel *line1 = [[MYLabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textView.frame) + 61, (SCREEN_width - 120)/2.0, 1)];
    [contentView addSubview:line1];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(line1.frame) + 20,CGRectGetMidY(line1.frame) - 12, 80, 20)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:font14];
    title.text = @"收费记录";
    [contentView addSubview:title];
    
    
    
    MYLabel *line2 = [[MYLabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(title.frame) + 20, CGRectGetMaxY(self.textView.frame) + 61, (SCREEN_width - 100)/2.0, 1)];
    [contentView addSubview:line2];
    
    
    ////////////// 底部收费记录 //////////////
    UIButton *recordView = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (self.pageType == PageTypeDetail) {
        
        [recordView setBackgroundImage:[UIImage imageWithColor:YAYIColor(210, 210, 210)] forState:UIControlStateHighlighted];
        recordView.frame = CGRectMake(0, CGRectGetMaxY(title.frame), SCREEN_width, 350 - CGRectGetMaxY(title.frame));
        [contentView addSubview:recordView];
        
        [recordView addTarget:self action:@selector(onRecordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.time = [[UILabel alloc] initWithFrame:CGRectMake(32, CGRectGetMaxY(line1.frame)+23, 120, 20)];
    self.time.font = [UIFont systemFontOfSize:font14];
    self.time.textColor = YAYIColor(87, 85, 85);
    self.time.text = @"时间：";
    [contentView addSubview:self.time];
    
    self.patient = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.time.frame), CGRectGetMaxY(self.time.frame) + 6, 160, 20)];
    self.patient.textColor = YAYIColor(87, 85, 85);
    self.patient.font = [UIFont systemFontOfSize:font14];
    self.patient.text = @"就诊人：张三";
    [contentView addSubview:self.patient];
    self.phone = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.time.frame), CGRectGetMaxY(self.patient.frame) + 6, 220, 20)];
    self.phone.textColor = YAYIColor(87, 85, 85);
    self.phone.font = [UIFont systemFontOfSize:font14];
    self.phone.text = @"联系电话：18977623430";
    [contentView addSubview:self.phone];
    self.hospital = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.time.frame), CGRectGetMaxY(self.phone.frame) + 6, 200 , 20)];
    self.hospital.textColor = YAYIColor(87, 85, 85);
    self.hospital.font = [UIFont systemFontOfSize:font14];
    self.hospital.text = @"天津市的倍儿口腔医院";
    [contentView addSubview:self.hospital];
    
    self.money = [[UILabel  alloc] initWithFrame:CGRectMake(SCREEN_width - 188, CGRectGetMinY(self.time.frame), 170, 20)];
    self.money.textAlignment = NSTextAlignmentRight;
    self.money.textColor = YAYIColor(87, 85, 85);
    self.money.font = [UIFont systemFontOfSize:font14];
    self.money.text = @"费用：¥70000.00";
    [contentView addSubview:self.money];
    
    if (self.pageType == PageTypeDetail) {
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_width - 20, CGRectGetMinY(self.hospital.frame), 7, 12)];
        icon.centerY = recordView.centerY;
        [icon setImage:[UIImage imageNamed:@"accessIcon"]];
        [contentView addSubview:icon];
    }
    
    
    return footerView;
}


-(void)createTableView
{
    if (self.tableView == nil) {
        self.tableView = [[YAYITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, SCREEN_height)];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableFooterView = [self footerView];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [self.view addSubview:self.tableView];
    }
}


-(void)createListView
{
    self.listView = [[YAYIListView alloc] initWithView:self.view.window];
    self.listView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.listView];
    
}


-(void)resignFirstResponderAction:(UITapGestureRecognizer *)tap
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES ];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self resignFirstResponder];
}


-(void)createDataSource
{
   
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *group0 = [NSMutableArray array];
        NSMutableArray *group1 = [NSMutableArray array];
        NSMutableArray *group2 = [NSMutableArray array];
        NSMutableArray *group3 = [NSMutableArray array];
        YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
        group.avatar = [NSString stringWithFormat:@"%@%@",API, _avatar];
        group.name = [NSString  stringWithFormat:@"%@ (%@)",_patientname,_clientname];
        group.phone = self.mobile;
        [group0 addObject:group];
        
        NSArray *titleAry = @[@"实退金额"];
        CGFloat shouldPayAmount = [self.totalPrice doubleValue] - [self.reduce doubleValue];
        if (self.pageType == PageTypeDetail) {
            shouldPayAmount = [self.reduce doubleValue];
        }
        
        self.realRefunds = [NSString stringWithFormat:@"%.2f", shouldPayAmount / 100.0];
        NSArray *name = @[[NSString stringWithFormat:@"%.2f", shouldPayAmount]];
        for (int i = 0; i< name.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = titleAry[i];
            group.name = name[i];
            [group1  addObject:group];
        }
        NSArray *title1 = @[@"收款方式"];
        NSArray *name1 = @[@"在线支付"];
        for (int i = 0; i< name1.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = title1[i];
            group.name = name1[i];
            [group2  addObject:group];
        }
        NSArray *title2 = @[@"退款原因"];
        NSArray *name2 = @[@""];
        for (int i = 0; i< name2.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = title2[i];
            group.name = name2[i];
            [group3  addObject:group];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataAry addObject:group0];
            [self.dataAry addObject:group1];
            [self.dataAry addObject:group2];
            [self.dataAry addObject:group3];
            [self.tableView  reloadData];
        });
    });
}


#pragma mark - 获取数据
/**
 *  获取订单详情，为了获取已退款金额（一个订单可以多次退款）
 */
- (void)getOrderInfo
{
    [YAYINetWorking getWithURL:didPay_order_detail_url param:@{@"orderid":self.orderid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"订单详情：%@", dict);
        if (nil == error) {
            
            // 算出已退金额
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSArray *refundDictArray = dict[@"map"][@"refund"];
                for (NSDictionary *dictItem in refundDictArray) {
                    self.hadRefundAmount += [dictItem[@"money"] integerValue];
                }
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                YAYIOrderRefundsCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                if (self.pageType == PageTypeRedund)
                {
                    cell.moneyText.text = [NSString stringWithFormat:@"%.2f", (self.totalPrice.integerValue - self.hadRefundAmount- self.reduce.integerValue) / 100.0];
                }else if (self.pageType == PageTypeDetail){
//                    cell.moneyText.text = [NSString stringWithFormat:@"%.2f", self.hadRefundAmount / 100.0];
                }
                
            }
        }else{
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", dict);
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
        
    }];
}


-(void)getUserInfo{
    
    YAYILog(@"userid:%@", self.userid);
    
    [YAYINetWorking getWithURL:patientDetail_url param:@{@"userid":self.userid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if (nil == error) {
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSString *avatar = dict[@"data"][@"avatar"];
                self.avatar = avatar;
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                YAYIAvatarCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                
                [cell.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", API, avatar]] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                }];
            }
        }else{
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", dict);
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
        
    }];
    
}


/**
 *  用户登录, 退款之前先调用登录
 */
-(void)userLlogin
{
    
    if (self.orderid == nil) {
        return ;
    }
    if (self.textView.text.length == 0) {
        self.textView.text = @" ";
    }
    if (self.type.length == 0) {
        [SVProgressHUD showImage:nil status:@"\n\n请选择退款原因\n\n"];
        return;
    }
    
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *username = [userdef stringForKey:YAYIUsernameKey];
    NSString *password = [userdef stringForKey:YAYIPasswordKey];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *versionStr = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = username;
    param[@"password"] = password;
//    param[@"deviceid"] = [CloudPushSDK getDeviceId];
    param[@"systemid"] = @"2";
    param[@"versions"] = versionStr;
    param[@"role"] = @(2);
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:userLogin_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            
            YAYILog(@"返回：%@", dict);
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                [self refunds];
            }else{
                
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
            }
            
        }else{
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"dict:%@", dict);
            
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
    }];
}

/**
 *  进入退款页面, 进入退款界面之前先调此接口
 */
- (void)getRefundInfo
{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"orderid"] = self.orderid;
    
    
    [YAYINetWorking getWithURL:refunds_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"返回：%@", dict);
        
        if (error == nil) {
            if ([dict[@"status"] isEqualToString:@"success"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self createHudView:@"提交失败"];
            }
        }else{
//            NSString *message = responseError[@"message"];
//            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}


/**
 *  提交退款
 */
-(void)refunds
{

    NSInteger priceCoin = (NSInteger)([self.realRefunds doubleValue] * 100);
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"orderid"] = self.orderid;
    param[@"money"] = @(priceCoin);
    
    param[@"operatorid"] = @"";
    param[@"type"] = self.type;
    param[@"remark"] = self.textView.text;
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:refunds_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        
         YAYILog(@"返回：%@", dict);
        
        if (error == nil) {
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                
                [SVProgressHUD showImage:nil status:@"\n\n退款成功\n\n"];
                
                __block typeof(self) weakself = self;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    if (self.refreshOperation) {
                        weakself.refreshOperation();
                    }
                    
                    [weakself.navigationController popViewControllerAnimated:YES];
                });
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"提交失败"];
            }
        }else{
            YAYILog(@"responseError：%@", responseError);
            NSString *message = responseError[@"message"];
            [SVProgressHUD showErrorWithStatus:message];
        }
        
    }];
}


- (void)getRefunds
{
    [YAYINetWorking getWithURL:refunds_reason param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"返回:%@", dict);
        
        if ([dict[@"status"] isEqualToString:@"success"]) {
        
            NSDictionary *map = dict[@"map"];
//            NSString *key = [NSString stringWithFormat:@"%@", self.noPayModel.refundstate];
            NSString *refundStr = map[self.refundstate];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
            YAYIOrderRefundsCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.name.text = refundStr;
        }
    }];
}


/**
 *  获取退款原因
 */
-(void)getRefundsReason
{
    
    if (self.refundsReasonArray.count > 0) {
        
        YAYIActionSheet *actionSheet = [[YAYIActionSheet alloc] initWithDelegate:self cancelButtonTitle:@"取消" otherButtonTitles:self.refundsReasonArray];
        
        [actionSheet show];
        return;
    }
    
    [YAYINetWorking getWithURL:refunds_reason param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"返回：%@", dict);
        if ([dict[@"status"] isEqualToString:@"success"]) {
            NSDictionary *map = dict[@"map"];
            
            [self.refundsReasonArray addObject:map[@"1"]];
            [self.refundsReasonArray addObject:map[@"2"]];
            [self.refundsReasonArray addObject:map[@"3"]];
            [self.refundsReasonArray addObject:map[@"4"]];
            
            YAYIActionSheet *actionSheet = [[YAYIActionSheet alloc] initWithDelegate:self cancelButtonTitle:@"取消" otherButtonTitles:self.refundsReasonArray];
            
            [actionSheet show];
        }
    }];
    
}


#pragma mark - 按钮执行方法
/**
 *  提交
 */
-(void)onSubmitBtnClick:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    
    // 判断是否0 < 实退金额 <= 优惠后金额
    CGFloat realPay = ([self.totalPrice doubleValue] - [self.reduce doubleValue] - self.hadRefundAmount) / 100.0;
    CGFloat realRefunds = [self.realRefunds doubleValue];
    
    if (realRefunds <= 0.00) {
        
        [SVProgressHUD showImage:nil status:@"\n\n实退金额必须大于0\n请重新填写\n\n"];
        [self.realRefundsTF becomeFirstResponder];
        return;
    }else if (realRefunds < 0.01){
        
        [SVProgressHUD showImage:nil status:@"\n\n实退金额不能小于0.01元\n请重新填写\n\n"];
        [self.realRefundsTF becomeFirstResponder];
        return;
    }else if ((realPay - realRefunds) < 0){
    
        if (self.pageType == PageTypeRedund)
        {
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n可退金额不足%.2f元\n\n", realRefunds]];
            [self.realRefundsTF becomeFirstResponder];
            return;
        }
        
        [SVProgressHUD showImage:nil status:@"\n\n实退金额不能大于优惠后金额\n请重新填写\n\n"];
        [self.realRefundsTF becomeFirstResponder];
        return;
    }
    

    NSString *msgStr = [NSString stringWithFormat:@"本单合计实退%.2f元，确定提交吗？", realRefunds];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:msgStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}


- (void)onRecordBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString *identifer = @"avatarCell";
        YAYIAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIAvatarCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.phone.text = model.phone;
        cell.name.text =  model.name;
        cell.icon.hidden = NO;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        static NSString *identifer = @"identifer";
        YAYIOrderRefundsCell *cell = [tableView  dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIOrderRefundsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        cell.row = indexPath.row;
        cell.backgroundColor = [UIColor whiteColor];//[UIColor colorWithWhite:0.965 alpha:1];
        YAYIGroupModel *model = self.dataAry[indexPath.row][0];
        cell.title.text = model.title;
        
        if (indexPath.row == 1) {
            CGFloat price = [model.name floatValue] / 100.0;
            cell.moneyText.text = [NSString stringWithFormat:@"%.2f", price];
            cell.moneyText.tag = 100;
            cell.moneyText.delegate = self;
            self.realRefundsTF = cell.moneyText;
            
        }else{
            cell.name.text = [NSString stringWithFormat:@"%@",model.name];
        }
        

        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (self.noPayModel) {
            
            if (indexPath.row == 4) {
                
                
            }
            self.textView.text = self.ordercontent;
            [self textViewDidChange:self.textView];
        }
        
        return cell;
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 80;
    }else{
        return 55;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.pageType == PageTypeDetail && indexPath.row != 0) {
        return;
    }
    
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    if (indexPath.row == 3) {
        
        // 选择退款原因
//        [self createListView];
        [self getRefundsReason];
    }else if (indexPath.row == 0){
    
        YAYIPatienInfoController *patientInfoVc = [[YAYIPatienInfoController alloc] init];
        patientInfoVc.isAccepted = YES;
        patientInfoVc.userid = [NSString stringWithFormat:@"%@", self.userid];
        YAYILog(@"patientInfoVc.userid:%@", patientInfoVc.userid);
        [self.navigationController pushViewController:patientInfoVc animated:YES];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (self.noPayModel) {
        
        return NO;
    }
    
    return YES;
}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 100) { //实退金额
        
        self.realRefunds = textField.text;
    }
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
   
    [textField resignFirstResponder];
    return YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if (self.noPayModel) {
        
        return NO;
    }else{
    
        self.view.y -= 120;
        return YES;
    }
}


-(void)textViewDidEndEditing:(UITextView *)textView
{
   self.view.y +=120;
}


-(void)textViewDidChange:(UITextView *)textView
{
    if (textView.tag == 100) { // 实退金额
        
        
    }else if (textView.tag == 200){ // 备注
    
        if (textView.text.length > 0) {
            self.placeholder.hidden = YES;
        }else{
            self.placeholder.hidden = NO;
        }
        
        if (textView.text.length < 50) {
            self.count.text = [NSString stringWithFormat:@"%ld / 50字",(50 - textView.text.length)];
        }else{
            textView.text =[textView.text substringWithRange:NSMakeRange(0, 49)];
            return;
        }
    }
}

#pragma mark UIAlertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    [self.view endEditing:YES];
    if (1 == buttonIndex) {
//        [self refunds];
//        [self getRefundInfo];
        [self userLlogin];
    }
}

#pragma mark 自定义选择列表代理
-(void)didselecedRow:(NSInteger)index content:(NSString *)contentStr
{
    self.type = [NSString stringWithFormat:@"%ld",index];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    YAYIOrderRefundsCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.name.text = contentStr;
}


#pragma mark 自定义选择列表代理
//-(void)alertView:(YAYIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    alertView = nil;
//    self.alertView = nil;
//    if (buttonIndex == 2) {
//        [self refunds];
//    }
//}

#pragma mark YAYIActionSheetDelegate代理
- (void)actionSheet:(YAYIActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)index
{
    self.type = [NSString stringWithFormat:@"%ld",index + 1];
    NSString *refuseReasonStr = self.refundsReasonArray[index];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    YAYIOrderRefundsCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.name.text = refuseReasonStr;
}

@end
